<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="root">
        <ul>
        <li>
            <a href="/home">首页</a>
        </li>
        <li>
            <a href="/about">关于</a>
        </li>
    </ul>
    </div>
    <script>
        const routes = [
            {
                path: '/home',
                component: () => {
                    return '<h1>首页</h1>'
                },
            },
            {
                path: '/about',
                component: () => {
                    return '<h1>关于</h1>'
                }
            }
        ]
        let root = document.getElementById('root')
        window.addEventListener('DOMContentLoaded',()=>{
            onload()
        })
        window.addEventListener('popstate',()=>{
            render(location.pathname)
        })
        function onload(){
            let linklist = document.querySelectorAll('a[href]')//进入浏览器
            linklist.forEach(el=>{
                el.addEventListener('click',(e)=>{
                    e.preventDefault()//阻止默认行为
                    let href = el.getAttribute('href')//读取属性
                    history.pushState(null,href,href)
                    console.log(location.pathname)
                    render(location.pathname)
                })    
            })
        }
        function render(url){
            let component = routes.find(item=>item.path === url)
            console.log(component)
            if(component){
                root.innerHTML = component.component()
            }
        }
    </script>
</body>

</html>